<template>
  <div v-loading="loadingRef" ref="chartRef" :style="{ height, width }"></div>
</template>

<script lang="ts" setup>
import { onMounted, ref, Ref } from 'vue';
import { useECharts } from '@/hooks/web/useECharts';
import type { EChartsOption } from 'echarts';

const chartRef = ref<HTMLDivElement | null>(null);
const loadingRef = ref(false)
const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);
defineProps({
  width: {
    type: String as PropType<string>,
    default: '100%',
  },
  height: {
    type: String as PropType<string>,
    default: '100%',
  },
})

const options: EChartsOption = {
  backgroundColor: '#fff',
  tooltip: {
    trigger: 'axis',
    appendToBody: true,
    axisPointer: {
      type: 'shadow',
      label: {
        show: true,
        backgroundColor: '#333',
      },
    },
  },
  grid: {
    top: '10px',
    left: '10px',
    right: '10px',
    bottom: '10px',
    containLabel: true,
  },
  yAxis: {
    type: 'value'
  },
  xAxis: {
    type: 'category',
    data: []
  },
  series: []
}

onMounted(() => {
  setOptions(options);
});

const setData = (xData, yData, hideEffciency) => {
  const op: EChartsOption = hideEffciency ? {
    graphic: {
      type: 'text',
      left: 'center',
      top: 'center',
      style: {
        text: '稼动率不支持按日查询',
        fill: '#d3d3d3',
        fontSize: 20,
      }
    },
  } : {
    ...options,
    xAxis: {
      type: 'category',
      data: xData
    },

    series: yData,
  }

  setOptions({
    ...op
  });
}
const getData = (fn, hideEffciency = false) => {
  loadingRef.value = true;
  fn.then(res => {
    const yData = res.yaxisList.map(item => ({
      ...item,
      type: 'bar',
      barMaxWidth: 30,
    }))
    setData(res.xaxisList, yData, hideEffciency)
  }).catch(e => {
    setData([], [], hideEffciency)
  }).finally(() => {
    loadingRef.value = false;
  })
}

defineExpose({
  getData
})

</script>